<template>
    <view>
        <u-toast ref="uToast" /><u-no-network></u-no-network>
        <u-navbar title="商品编辑" safeAreaInsetTop fixed placeholder>
            <view class="coreshop-navbar-left-slot" slot="left">
                <u-icon name="arrow-left" size="19" @click="goNavigateBack"></u-icon>
                <u-line direction="column" :hairline="false" length="16" margin="0 8px"></u-line>
                <u-icon name="home" size="22" @click="goHome"></u-icon>
            </view>
            <view slot="right">
            </view>
        </u-navbar>
        <view class="content">
            <view class="coreshop-tabbar-height">
                <view class='img-list'>
<!--                    <view v-for="item in info.items" :key="item.id"> -->
                        <view class="coreshop-bg-white coreshop-card-box coreshop-margin-10">
                            <view class="coreshop-card-view coreshop-order-view">
                                <view class="coreshop-font-md coreshop-text-bold coreshop-text-black">商品信息</view>
                                <u-line color="#eee" border-style="dashed" margin="10px 0" />
                                <view class="evaluate-c-f">
                                  <text @click="show = true">{{finalAddress == '' ? "请选择商品类别": finalAddress}}</text>
								  <u-picker :show="show" ref="uPicker" :columns="columns"  @confirm= "sureChoose" @cancel="cancelChoose" @change="changeHandler"></u-picker>
                                </view>  
                            </view>

							
                            <view class="coreshop-card-view coreshop-order-view">
                                <view class="coreshop-font-md coreshop-text-bold coreshop-text-black">商品名称</view>
                                <u-line color="#eee" border-style="dashed" margin="10rpx 0" />
                                <view class="evaluate-c-f">
                                    <input v-model="name" placeholder="名称" />
                                </view>
                            </view>								
							
                            <!-- <view class="coreshop-card-view coreshop-order-view">
                                <view class="coreshop-font-md coreshop-text-bold coreshop-text-black">型号规格</view>
                                <u-line color="#eee" border-style="dashed" margin="10rpx 0" />
                                <view class="evaluate-c-f">
                                    <input v-model="specs" placeholder="规格" />
                                </view>
                            </view> -->									
							
                            <view class="coreshop-card-view coreshop-order-view">
                                <view class="coreshop-font-md coreshop-text-bold coreshop-text-black">计量单位</view>
                                <u-line color="#eee" border-style="dashed" margin="10rpx 0" />
                                <view class="evaluate-c-f">
                                    <input v-model="unit" placeholder="单位" />
                                </view>
                            </view>								
							
                            <view class="coreshop-card-view coreshop-order-view">
                                <view class="coreshop-font-md coreshop-text-bold coreshop-text-black">成本价</view>
                                <u-line color="#eee" border-style="dashed" margin="10rpx 0" />
                                <view class="evaluate-c-f">
                                    <input v-model="costprice" type="digit" inputmode="decimal" placeholder="成本价" />
                                </view>
                            </view>									
							
                            <view class="coreshop-card-view coreshop-order-view">
                                <view class="coreshop-font-md coreshop-text-bold coreshop-text-black">销售价</view>
                                <u-line color="#eee" border-style="dashed" margin="10rpx 0" />
                                <view class="evaluate-c-f">
                                    <input v-model="price" type="digit" inputmode="decimal" placeholder="销售价" />
                                </view>
                            </view>									
							
                            <view class="coreshop-card-view coreshop-order-view">
                                <view class="coreshop-font-md coreshop-text-bold coreshop-text-black">市场价</view>
                                <u-line color="#eee" border-style="dashed" margin="10rpx 0" />
                                <view class="evaluate-c-f">
                                    <input v-model="mktprice" type="digit" inputmode="decimal" placeholder="这里录入市场价" />
                                </view>
                            </view>								
							
                            <view class="coreshop-card-view coreshop-order-view">
                                <view class="coreshop-font-md coreshop-text-bold coreshop-text-black">商品描述</view>
                                <u-line color="#eee" border-style="dashed" margin="10px 0" />
                                <view class="evaluate-c-t">
                                    <textarea v-model="brief" placeholder="这里录入商品描述" />
                                </view>
                            </view>
                            <view class="coreshop-card-view coreshop-order-view">
                                <view class="coreshop-font-md coreshop-text-bold coreshop-text-black">商品图片（可上传{{maxUploadImg}}张）</view>
                                <u-line color="#eee" border-style="dashed" margin="10px 0" />
                                <view class="evaluate-c-b">
                                    <view class="goods-img-item" v-if="images.length" v-for="(img, key) in images" :key="key">
                                        <image class="del" src="/static/images/common/del.png" mode="" @click="removeImg(key)"></image>
                                        <image class="" :src="img" mode="" @click="clickImg(img)"></image>
                                    </view>
                                    <view class="upload-img" v-show="isupload">
                                        <image class="icon" src="/static/images/common/camera.png" mode="" @click="uploadImg()"></image>
                                        <view class="">拍照上传</view>
                                    </view>
                                </view>
                            </view>
							
                            <view class="coreshop-card-view coreshop-order-view">
                                <view class="coreshop-font-md coreshop-text-bold coreshop-text-black"></view>
                                <view class="evaluate-c-t">
                                </view>
                            </view>							
							
                        </view>
<!--                    </view> -->
                </view>
            </view>
        </view>
        <view class="coreshop-foot-hight-view" />
        <view class="coreshop-bg-white coreshop-footer-fixed coreshop-foot-padding-bottom coreshop-padding-5">
            <u-button type="error" size="normal" @click="toEvaluate" :disabled='submitStatus' :loading='submitStatus'>编辑保存</u-button>
		
        </view>
		<!-- 登录提示 -->
		<!-- <coreshop-login-modal></coreshop-login-modal> -->
    </view>

</template>

<script>

    export default {

        data() {
            return {
                customStyle: {
                    width: '100%',
                },
			    	mode: 'single-column',
		        	defaultSelector: [0],	
					name:'',//采集人员名称
					specs:'',//事件描述
					unit:'',
					price:'0', 
					mktprice:'0',
					costprice:'0',
					brief:'',
					image:'',
					goodsType:'',
					goodsCategoryId:'0',	
				    goodsCategory:'',
					selectShow: true,
					selectList:['T','F'],
					
                goodsId: 0, // 商品id
                goodsInfo: {}, // 商品详情					
					
                show: false,
				columns: [
					[],
					[]
				],
				columnData: [
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[]
				                ],
				    finalAddress: '',

					orderId: 0,
					info: {}, // 订单详情
					images: [],
					score: [], // 商品评价
					textarea: [], // 商品评价信息
					isupload: [], // 启/禁用 图片上传按钮
					rate: 5,
					submitStatus: false
            }					
        },
        
		onLoad(options) {
            this.categories ();	
				
            //获取商品ID
            if (options.id != '') {
                this.goodsId = options.id;
            }
			
			this.getGoodsDetail();				
							
				// let userToken = this.$db.get("userToken");
				// console.log(userToken);
				// console.log("1111");

        },
		
        onShow() {

        },	
			
        computed: {
            // 获取vuex中状态
            maxUploadImg() {
                return this.$store.state.config.imageMax				
				//return 9
            }
        },
        methods: {

            changeAddress(e) {
				
				console.log(e)
			    const that = this;				
				let { columnIndex, indexs} = e
				console.log(columnIndex,indexs)
				
				//if(columnIndex==0) {
					// 在mounted里面手动调用一次，初始数据的渲染
					// 通过indexs[0]获取二级列表的数据，返回数据填充到address数组的第二列，加入获取的数据为下
					// rsp.data[indexs[0]].id
					// 获取数据
					// that.address[1].push('北京市')
					// that.address[1].push('上海市')
					// that.address[1].push('天津市')				
				//}
				
				//if(columnIndex==1) {
					// 通过indexs[1]获取三级列表的数据，返回数据填充到address数组的第三列，加入获取的数据为下
					// rsp.data[indexs[1]].id
					// 获取数据
				// 	 that.address[2].push('钟山区')
				// 	 that.address[2].push('凤凰区')
				// 	 that.address[2].push('黄土坡')
					
				// }
			},
			
			sureChoose(e) {
				this.show = false
				this.finalAddress = e.value[0] + '/'+ e.value[1] 
				this.goodsType = e.value[1]
				this.goodsCategory = e.value[1]
				console.log(e)
				
			},
			
			cancelChoose(e) {
				this.show = false
				console.log(e)
			},	
						
			// 选择商品类型回调
			selectConfirm(e) {
				this.goodsType = '';
				this.goodsCategoryId = '0';				
				e.map((val, index) => {
					this.goodsType += this.goodsType == '' ? val.label : '-' + val.label;
					this.goodsCategoryId = val.value;					
				})
			},
			
            categories() {
                this.$u.api.categories().then(res => {
                    if (res.status) {
                        this.tabbar = res.data;
						
						//console.log(res.data);
													
						res.data.forEach((item, key) => {
							
							let model = {
								ItemId: key,								
								value: item.id,
								label: item.name
							}							
							this.columns[0].push(item.name);
							
							//console.log("key:" + key);
							
							item.child.forEach((item1, key1) => {
								
								if (key == 0) {
								this.columns[1].push(item1.name);
								}
								
						        //console.log(this.columns[1]);								
								
								this.columnData[key].push(item1.name);
								
							})
						
						})	
                    }
                });
            },
						
            childscategories() {
                this.$u.api.childscategories().then(res => {
                    if (res.status) {
                        //this.selectList = res.data;
						res.data.forEach((item, key) => {
							let model = {
								ItemId: key,								
								value: item.id,
								label: item.name
							}
							this.address[0].push(item.name);
						})	
									
                    }
                });
            },
			
            changeHandler(e) {
                const {
                    columnIndex,
                    value,
                    values, // values为当前变化列的数组内容
                    index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
                    picker = this.$refs.uPicker
                } = e
                // 当第一列值发生变化时，变化第二列(后一列)对应的选项
                if (columnIndex === 0) {
                    // picker为选择器this实例，变化第二列对应的选项
                    picker.setColumnValues(1, this.columnData[index])
                }
            
			},
	
            // 获取商品详情
            getGoodsDetail() {	
                let _this = this;
                let data = {
                    id: parseInt(this.goodsId),
                    data: true
                }
                // 如果用户已经登录 要传用户token
                let userToken = this.$db.get("userToken");
                if (userToken) {
                    this.$u.api.goodsDetailByToken(data).then(res => {
                        if (res.status == true) {
                            let info = res.data;
                            _this.product = res.data.product;
                            _this.goodsInfo = info;
                            _this.goodsSkuInfo = res.data.skuList;
							
                            _this.name = res.data.name;		
							_this.specs = res.data.newSpec;
							_this.unit = res.data.unit;
							_this.price = res.data.price;
							_this.mktprice = res.data.mktprice;
							_this.costprice = res.data.costprice;
							_this.brief = res.data.brief;
								
							_this.goodsCategoryId = res.data.goodsCategoryId;
							_this.goodsCategory = res.other;						
																
							_this.finalAddress	= res.other;	
															
							//加载图片		
					    	if (res.data.images !=='undefined' && res.data.images !== null && res.data.images !== '') {
								
								//let strArr = ['https://fpapi.milane.com.cn//upload/20240813/20240813134015_9928.jpg','https://fpapi.milane.com.cn//upload/20240813/20240813134844_6618.jpg'];
							    const strArr = res.data.images.split(',')
								
								for(var i = 0; i < strArr.length; i++) {
									
								_this.images.push(strArr[i]);	
								
								}
														
							    //strArr.forEach((item) => {
								//_this.images.push(strArr[]);	
						    //};
							
							//console.log(strArr);									
					        }
							
                            console.log(info);							
							
                            if (res.otherData.agentProducts) {
                                for (var i = 0; i < res.otherData.agentProducts.length; i++) {
                                    for (var j = 0; j < res.data.skuList.sku_list.length; j++) {
                                        if (res.data.skuList.sku_list[j]._id == res.otherData.agentProducts[i].productId) {
                                            res.otherData.agentProducts[i].name = res.data.skuList.sku_list[j].sku_name_arr[0];
                                            break;
                                        }
                                    }
                                }
                                console.log(res.otherData.agentProducts);
                                _this.agentProducts = res.otherData.agentProducts;
                            }

                            if (res.otherData && res.otherData.userAgentGrade) {
                                _this.userAgentGrade = res.otherData.userAgentGrade;
                            } else {
                                _this.userAgentGrade = null;
                            }

                            if (res.otherData && res.otherData.userAgent) {
                                _this.userAgent = res.otherData.userAgent;
                            } else {
                                _this.userAgent = null;
                            }

                            //价格区间
                            if (res.data.minPrice != res.data.maxPrice) {
                                _this.priceSection = res.data.minPrice + '~' + res.data.maxPrice;
                            } else {
                                _this.priceSection = res.data.product.mktprice;
                            }

                            if (_this.goodsInfo.album) {
                                var albums = [];
                                for (var i = 0; i < _this.goodsInfo.album.length; i++) {
                                    let album = {
                                        url: _this.goodsInfo.album[i],
                                        type: 'image'
                                    }
                                    albums.push(album);
                                }
                                _this.goodsInfo.album = albums;
                                if (_this.goodsInfo.video) {
                                    let videoObj = {
                                        url: _this.goodsInfo.video,
                                        poster: _this.goodsInfo.image,
                                        type: 'video'
                                    }
                                    _this.goodsInfo.album.unshift(videoObj);
                                    _this.autoplay = false;
                                }
                            }
                            _this.isfav = res.data.isFav;
                            // 判断如果登录用户添加商品浏览足迹
                            //if (userToken) {
                            //    _this.goodsBrowsing();
                            //}
                        } else {
                            _this.$refs.uToast.show({
                                message: res.msg, type: 'error', complete: function () {
                                    uni.navigateBack({
                                        delta: 1
                                    });
                                }
                            })
                        }
                    })
                } else {
                    this.$u.api.goodsDetail(data).then(res => {
                        if (res.status == true) {
                            _this.goodsInfo = res.data;
                            _this.product = res.data.product;
                            _this.goodsSkuInfo = res.data.skuList;

                            if (res.otherData && res.otherData.userAgentGrade) {
                                _this.userAgentGrade = res.otherData.userAgentGrade;
                            } else {
                                _this.userAgentGrade = null;
                            }

                            if (res.otherData && res.otherData.userAgent) {
                                _this.userAgent = res.otherData.userAgent;
                            } else {
                                _this.userAgent = null;
                            }

                            //价格区间
                            if (res.data.minPrice != res.data.maxPrice) {
                                _this.priceSection = res.data.minPrice + '~' + res.data.maxPrice;
                            } else {
                                _this.priceSection = res.data.product.mktprice;
                            }

                            if (_this.goodsInfo.album) {
                                var albums = [];
                                for (var i = 0; i < _this.goodsInfo.album.length; i++) {
                                    let album = {
                                        url: _this.goodsInfo.album[i],
                                        type: 'image'
                                    }
                                    albums.push(album);
                                }
                                _this.goodsInfo.album = albums;
                                if (_this.goodsInfo.video) {
                                    let videoObj = {
                                        url: _this.goodsInfo.video,
                                        poster: _this.goodsInfo.image,
                                        type: 'video'
                                    }
                                    _this.goodsInfo.album.unshift(videoObj);
                                    _this.autoplay = false;
                                }
                            }
                            _this.isfav = res.data.isFav;
                            // 判断如果登录用户添加商品浏览足迹
                            //if (userToken) {
                            //    _this.goodsBrowsing();
                            //}
                        } else {
                            _this.$refs.uToast.show({
                                message: res.msg, type: 'error', complete: function () {
                                    uni.navigateBack({
                                        delta: 1
                                    });
                                }
                            })
                        }
                    })
                }
            },	
			
	
				// 获取订单详情
				orderInfo() {
                let data = {
                    id: this.orderId
                }
				
                this.$u.api.orderDetail(data).then(res => {
                    if (res.status && res.data.payStatus >= 2 && res.data.shipStatus >= 3 && res.data.confirmStatus >= 2 && res.data.isComment === false) {
                        const _info = res.data
                        let images = []
                        let textarea = []
                        let upload = []
                        let score = []
                        _info.items.forEach(item => {
                            images[item.id] = []
                            textarea[item.id] = ''
                            upload[item.id] = true
                            score[item.id] = 5
                        })
                        this.info = _info
                        this.images = images
                        this.textarea = textarea
                        this.score = score
                        this.isupload = upload
                    } else {
                        this.$u.toast('订单不存在或状态不可评价!')
                    }
                })
            },
			
						
            // 上传图片
            uploadImg() {
                this.$upload.uploadFiles(null, res => {
                    if (res.status) {
                        //this.images[key].push(res.data.src + '?x-oss-process=image/resize,m_lfit,h_200,w_200')
                        this.images.push(res.data.src)
						
                        this.$refs.uToast.show({ title: res.msg, type: 'success', back: false })
						
					    console.log(this.images)						
                    } else {
                        this.$u.toast(res.msg)
                    }
                })
            },
			
			
            // 删除图片
            removeImg(key) {
                this.images.splice(key, 1)
            },
            // 图片点击放大
            clickImg(img) {
                // 预览图片
                uni.previewImage({
                    urls: img.split()
                });
            },

            // 提交评价
            toEvaluate() {
                let _this = this;				
                this.submitStatus = true;
                let items = [];
				let _str ='';

                this.images.forEach((item, key) => {
                    let model = {
                        orderItemId: key,
                        images: item,
                        score: _this.score[key],
                        textarea: _this.textarea[key]
                    }
                    items.push(model);
                })
				
                for (var k = 0; k < _this.images.length; k++) {
                  _str += _this.images[k] + ","
                } 
                  _str= _str.substring(0, _str.lastIndexOf(','));	
					
				if (_this.finalAddress == '') {
					_this.$u.toast('请选择商品分类！')
                    _this.submitStatus = false;					
					return false
				}
					
				if (_this.name == '') {
					this.$u.toast('请输入商品名称！')
                    _this.submitStatus = false;						
					return false	
				}
							
                let data = {
                    //orderId: _this.orderId,
                    //items: items
					id:_this.goodsId,
					name:_this.name,
					specs:_this.specs,					
					unit:_this.unit,
					price:_this.price,
					mktprice:_this.mktprice,
					costprice:_this.costprice,
					brief:_this.brief,
					images:_str,
					image:_this.images[0],
					goodsCategoryId: _this.goodsCategoryId,
					goodsCategory: _this.goodsCategory,
                }
				console.log(data);
				
                this.$u.api.GoodsEdit(data).then(res => {
                    if (res.code == 0) {
                        _this.submitStatus = false;							
						//this.$refs.uToast.show({ title: '上架成功', type: 'success', back: true })
						this.$refs.uToast.show({
							message: '编辑成功', type: 'success', complete: function () {
								uni.navigateBack({
									delta: 1
								});
							}
						})						
						
                    } else {
                        _this.$u.toast(res.msg)
                    }
                });
            }
			
			
		
		},
		
		
        watch: {
            images: {
                handler() {
                    this.images.forEach((item, key) => {
                        this.isupload[key] = item.length >= this.maxUploadImg ? false : true
                    })
                },
                deep: true
            }
        }
    }
</script>

<style lang="scss" scoped>
    @import "grounding.scss";
</style>
